package com.atguigu.demo03;




import ch.qos.logback.core.pattern.FormatInfo;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author gjl
 * @create 2021-04-26 20:36
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();

        for (int i = 0; i < 10; i++) {
            int finalI = i;
            new Thread(()->{
                myCache.write(finalI +"", finalI+"");
            },String.valueOf(i)).start();
        }

        for (int i = 0; i < 10; i++) {
            int finalI = i;
            new Thread(()->{
                myCache.read( finalI +"");
            },String.valueOf(i)).start();
        }
    }


}
class MyCache{
    Map<String,String> map = new ConcurrentHashMap<>();
    private Lock lock= new ReentrantLock();
    ReentrantReadWriteLock rwl =  new ReentrantReadWriteLock();

    public void write(String key,String value){

        rwl.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"正在写");
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"完成写");

        } finally {
            rwl.writeLock().unlock();
        }
    }

    public void read(String key){

        rwl.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"正在读");
            map.get(key);
            System.out.println(Thread.currentThread().getName()+"完成读");

        } finally {
            rwl.readLock().unlock();
        }
    }

}
